const canvas = document.querySelector('canvas');

canvas.height = window.innerHeight;
canvas.width = window.innerWidth;

const context = canvas.getContext("2d");

const colorArray = ['rgb(255,248,220)',
    'rgb(255,235,205)',
    'rgb(255,228,196)',
    'rgb(255,222,173)',
    'rgb(245,222,179)',
    'rgb(222,184,135)',
    'rgb(210,180,140)',
    'rgb(188,143,143)'];

class Mouse {
    constructor() {
        this.x = undefined;
        this.y = undefined;
    }
};

let mouse = new Mouse();

class Circle {
    constructor() {
        this.maxRadius = 50 + Math.random() * 10;
        this.minRadius = 5 + Math.random() * 10;
        this.radius = this.minRadius;

        this.posY = Math.random() * (canvas.height - this.radius * 2) + this.radius;
        this.posX = Math.random() * (canvas.width - this.radius * 2) + this.radius;

        let angle = Math.random() * Math.PI * 2;
        let speed = 2 + Math.random() * 2;
        this.vecY = speed * Math.sin(angle);
        this.vecX = speed * Math.cos(angle);

        this.strokeStyle = 'rgb(255, 64, 0)';     
        this.fillStyle = colorArray[(Math.random() * colorArray.length).toFixed()];
    }

    animate() {
        if (Math.abs(mouse.x - this.posX) < 150 && Math.abs(mouse.y - this.posY) < 100) {
            if (this.radius < this.maxRadius) {
                this.radius += 2.0;
            }
        }
        else if (this.radius > this.minRadius) {
            this.radius -= 0.2;
        }

        this.posY += this.vecY;
        this.posX += this.vecX;
        if (this.posY < this.radius || this.posY >= canvas.height - this.radius) {
            this.vecY = -this.vecY;
            this.posY += this.vecY;
        }

        if (this.posX < this.radius || this.posX >= canvas.width - this.radius) {
            this.vecX = -this.vecX;
            this.posX += this.vecX;
        }
    }

    draw() {
        context.beginPath();
        context.arc(this.posX, this.posY, this.radius, 0, Math.PI * 2, false);
        context.strokeStyle = this.strokeStyle;
        context.fillStyle = this.fillStyle;
        context.lineWidth = 4;
        context.stroke();
        context.fill();
    }
};

let circles = [];

for (let i = 0; i < 300; i++) {
    circles.push(new Circle());
}

function animate() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (let circle of circles) {
        circle.animate();
    }

    for (let circle of circles) {
        circle.draw();
    }

    requestAnimationFrame(animate);
}

animate();

window.addEventListener('mousemove', (event) => {
    mouse.x = event.x;
    mouse.y = event.y;
});

